package com.bupt.websocket.controller;

import com.bupt.websocket.bean.WebSocketResult;
import com.bupt.websocket.service.impl.StorageFileNotFoundException;
import com.bupt.websocket.service.StorageService;
import com.bupt.websocket.service.impl.WebPush;
import com.bupt.websocket.utils.ClientWeb;
import com.bupt.websocket.utils.IkariUtils;
import com.jyt.message.Message;
import com.jyt.util.MySerializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.util.stream.Collectors;

import com.bupt.websocket.service.StorageService;
import com.bupt.websocket.service.impl.StorageFileNotFoundException;

@Controller
public class FileUploadController {

    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/showUploadFileList")
    public String listUploadedFiles(Model model) throws IOException {

        model.addAttribute("files", storageService.loadAll().map(
                path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class,
                        "serveFile", path.getFileName().toString()).build().toString())
                .collect(Collectors.toList()));

        return "uploadForm";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    @PostMapping("/sendFile")
    @ResponseBody
    public WebSocketResult handleFileUpload(@RequestParam("file") MultipartFile file,
                                   @RequestParam String uid, @RequestParam String to) {

        if (uid == null || to == null) {
            return new WebSocketResult(false);
        }


        //检测文件类型；
        String originalFilename = file.getOriginalFilename();
        if(originalFilename.equals("")||originalFilename==null){
            originalFilename = file.getName();
        }
        String extName = originalFilename.substring(originalFilename.indexOf("."));

        String fileType = "file";
        if(extName.equals(".jpg")||extName.equals(".png")||extName.equals(".jpeg"))fileType = "img";




        String FilePath = storageService.store(file);

        Message message1 = new Message();
        message1.setContent(MySerializable.object_bytes(FilePath));
        message1.setFrom(uid);
        message1.setTo(to);
        message1.setType("img");

        ClientWeb clientWeb = WebPush.clients2.get(uid);
        if(null!=clientWeb) {
            clientWeb.send(message1);
            return new WebSocketResult(true);
        }
        return new WebSocketResult(false);
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }

    @RequestMapping("modifyGroupAvatar")
    @ResponseBody
    public WebSocketResult modifyGroupAvatar(@RequestParam String groupid, @RequestParam("file") MultipartFile file, @RequestParam String uid) {

        String FilePath = storageService.store(file);

        String request = "{'groupid':'" + groupid + "','groupAvatar':'" + FilePath + "','uid':'" + uid + "'}";
        boolean isSuccess = IkariUtils.sendViWebPush(uid, "sys_groups", "modifyGroupAvatar", request);
        return new WebSocketResult(isSuccess);
    }

    @RequestMapping("modifyUserAvatar")
    @ResponseBody
    public WebSocketResult modifyUserAvatar(@RequestParam("file") MultipartFile file, @RequestParam String uid) {

        String FilePath = storageService.store(file);

        String request = "{'UserAvatar':'" + FilePath + "','uid':'" + uid + "'}";
        boolean isSuccess = IkariUtils.sendViWebPush(uid, "sys_groups", "modifyUserAvatar", request);
        return new WebSocketResult(isSuccess);
    }

    @RequestMapping("sendPicToOne")
    @ResponseBody
    public WebSocketResult sendPicToOne(@RequestParam("file") MultipartFile file,
                               @RequestParam String from,
                               @RequestParam String to,
                               @RequestParam String time) {

        //检测文件类型；
        String originalFilename = file.getOriginalFilename();
        if(originalFilename.equals("")||originalFilename==null){
            originalFilename = file.getName();
        }
        String extName = originalFilename.substring(originalFilename.indexOf("."));

        String fileType = "msg_pic";
        if(extName.equals(".jpg")||extName.equals(".png")||extName.equals(".jpeg")){}
            else fileType = "msg_file";




        String FilePath = storageService.store(file);
        String request = "{'content':'" + FilePath + "', 'from':'" + from + "', 'to':'" + to + "', 'time':'" + time + "'}";
        boolean isSuccess = IkariUtils.sendViWebPush(from, to, fileType, request);
        return new WebSocketResult(isSuccess);
    }

    @RequestMapping("sendPicToGroup")
    @ResponseBody
    public WebSocketResult sendPicToGroup(@RequestParam("file") MultipartFile file,
                                 @RequestParam String uid,
                                 @RequestParam String gid,
                                 @RequestParam String time, @RequestParam String avatar) {
        //检测文件类型；
        String originalFilename = file.getOriginalFilename();
        if(originalFilename.equals("")||originalFilename==null){
            originalFilename = file.getName();
        }
        String extName = originalFilename.substring(originalFilename.indexOf("."));

        String fileType = "groupMsg_pic";
        if(extName.equals(".jpg")||extName.equals(".png")||extName.equals(".jpeg")){}
        else fileType = "groupMsg_file";




        String FilePath = storageService.store(file);
        String request = "{'content':'" + FilePath + "', 'uid':'" + uid +"', 'avatar':'" + avatar + "', 'gid':'" + gid + "', 'time':'" + time + "'}";
        boolean isSuccess = IkariUtils.sendViWebPush(uid, "sys_groups", fileType, request);
        return new WebSocketResult(isSuccess);
    }


}
